package com.lijie.ljblog.util;

import com.lijie.ljblog.model.Music;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.id3.AbstractID3v2Frame;
import org.jaudiotagger.tag.id3.AbstractID3v2Tag;
import org.jaudiotagger.tag.id3.framebody.FrameBodyAPIC;

import java.io.File;

public class MusicUtils {

    /**
     * 获取歌曲信息构造Music对象
     *
     * @param file 歌曲路径
     * @return Music对象
     * @throws Exception Exception
     */
    public static Music getMusicInfo(File file) throws Exception {

        //mp3文件
        MP3File mp3File = (MP3File) AudioFileIO.read(file);
        AudioHeader audioHeader = mp3File.getAudioHeader();
        //标签
        Tag tag = mp3File.getID3v2TagAsv24();

        if (tag != null) {
            //歌曲名
            String musicName = tag.getFirst(FieldKey.TITLE);
            //歌手
            String artist = tag.getFirst(FieldKey.ARTIST);
            return new Music(musicName, artist);
        }
        return new Music();
    }

    /**
     * 获取MP3封面图片 二进制流
     *
     * @param mp3File mp3文件
     * @return 图片字节数组
     */
    public static byte[] getMp3Image(File mp3File) {
        byte[] imageData;
        try {
            MP3File mp3file = new MP3File(mp3File);
            AbstractID3v2Tag tag = mp3file.getID3v2Tag();
            AbstractID3v2Frame frame = (AbstractID3v2Frame) tag.getFrame("APIC");
            FrameBodyAPIC body;
            if (frame != null && !frame.isEmpty()) {
                body = (FrameBodyAPIC) frame.getBody();
                imageData = body.getImageData();
                return imageData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
